package com.ruoyi.common.utils;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.MimetypesFileTypeMap;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.*;
import java.util.Map.Entry;

public class HttpClientUtils
{
    final static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
    /**
     * 
     * 调用http(post)接口
     * @param Url
     * @param requestHeader
     * @param requestBody
     * @return
     * @throws IOException
     * <br/>==============History===============<br/>
     * 2019年7月22日   admin    新建
     */
    public static String doPost(String Url, Map<String, String> requestHeader, Map<String, Object> requestBody) throws IOException {
        // 创建一个httpclient对象
        try(CloseableHttpClient client = HttpClients.createDefault()){
            // 创建一个post对象
            HttpPost post = new HttpPost(Url);
            ObjectMapper mapper = new ObjectMapper();
            // 设置requestHeader参数
            Iterator iteratorHeader = requestHeader.entrySet().iterator();
            while (iteratorHeader.hasNext()) {
                Entry<String, String> elem = (Entry<String, String>) iteratorHeader.next();
                post.setHeader(elem.getKey(), elem.getValue());
            }
            // 设置requestBody参数
            StringEntity requestJson = new StringEntity(mapper.writeValueAsString(requestBody), "utf-8");
            requestJson.setContentType("application/json");
            post.setEntity(requestJson);
            CloseableHttpResponse response = client.execute(post);
            // 判断返回的状态
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            logger.warn("返回状态："+state);
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String json = EntityUtils.toString(responseEntity, "utf-8");
                response.close();
                client.close();
                return json;
            }
            response.close();
            client.close();
        }
        return null;
    }
    
    public static String doPost(String Url) throws IOException {
        // 创建一个httpclient对象
        try(CloseableHttpClient client = HttpClients.createDefault()){
	        // 创建一个post对象
	        HttpPost post = new HttpPost(Url);
	        ObjectMapper mapper = new ObjectMapper();
	        CloseableHttpResponse response = client.execute(post);
	        // 判断返回的状态
	        StatusLine status = response.getStatusLine();
	        int state = status.getStatusCode();
	        logger.warn("返回状态："+state);
	        if (state == HttpStatus.SC_OK) {
	            HttpEntity responseEntity = response.getEntity();
	            String json = EntityUtils.toString(responseEntity, "utf-8");
	            response.close();
	            client.close();
	            return json;
	        }
	        response.close();
	        client.close();
	    }
        return null;
    }
    
    public static String doDelete(String Url) throws IOException {
        // 创建一个httpclient对象
        try(CloseableHttpClient client = HttpClients.createDefault()){
	        // 创建一个post对象
	        HttpDelete post = new HttpDelete(Url);
	        ObjectMapper mapper = new ObjectMapper();
	       
	        CloseableHttpResponse response = client.execute(post);
	        // 判断返回的状态
	        StatusLine status = response.getStatusLine();
	        int state = status.getStatusCode();
	        logger.warn("返回状态："+state);
	        if (state == HttpStatus.SC_OK) {
	            HttpEntity responseEntity = response.getEntity();
	            String json = EntityUtils.toString(responseEntity, "utf-8");
	            response.close();
	            client.close();
	            return json;
	        }
	        response.close();
	        client.close();
        }
        return null;
    }

    public static String doGet(String Url, Map<String, String> requestHeader) throws IOException {
        // 创建一个httpclient对象
        try(CloseableHttpClient client = HttpClients.createDefault()){
	        // 创建一个post对象
	        HttpGet get = new HttpGet(Url);
	        ObjectMapper mapper = new ObjectMapper();
	        // 设置requestHeader参数
	        Iterator iteratorHeader = requestHeader.entrySet().iterator();
	        while (iteratorHeader.hasNext()) {
	            Entry<String, String> elem = (Entry<String, String>) iteratorHeader.next();
	            get.setHeader(elem.getKey(), elem.getValue());
	        }
	        CloseableHttpResponse response = client.execute(get);
	        // 判断返回的状态
	        StatusLine status = response.getStatusLine();
	        int state = status.getStatusCode();
	        logger.warn("返回状态："+state);
	        if (state == HttpStatus.SC_OK) {
	            HttpEntity responseEntity = response.getEntity();
	            String json = EntityUtils.toString(responseEntity, "utf-8");
	            response.close();
	            client.close();
	            return json;
	        }
	        response.close();
	        client.close();
        }
        return null;
    }
    
    /**
     * 
     * post文件请求
     * @param Url
     * @param requestHeader
     * @param requestBody
     * @param in
     * @param fileName
     * @return
     * @throws IOException
     * <br/>==============History===============<br/>
     * 2019年11月18日   admin    新建
     */
    public static String doPostMultipart(String Url, Map<String, String> requestHeader, Map<String, Object> requestBody, InputStream in, String fileName) throws IOException {
        //超时处理
        RequestConfig config = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(30000).setConnectionRequestTimeout(30000)
                .setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
        CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();
        //CloseableHttpClient client = HttpClients.createDefault();
        // 创建一个post对象
        HttpPost post = new HttpPost(Url);
        // 设置requestHeader参数
        Iterator iteratorHeader = requestHeader.entrySet().iterator();
        while (iteratorHeader.hasNext()) {
            Entry<String, String> elem = (Entry<String, String>) iteratorHeader.next();
            post.setHeader(elem.getKey(), elem.getValue());
        }
        String BOUNDARY = UUID.randomUUID().toString();
        post.addHeader("Content-Type", "multipart/form-data; boundary="+BOUNDARY);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        //字符编码
        builder.setCharset(Charset.forName("UTF-8"));
        //模拟浏览器
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        //boundary
        builder.setBoundary(BOUNDARY);
        //multipart/form-data 
        //builder.addPart("multipartFile",new FileBody(file));
        // binary //
        
        //builder.addBinaryBody("name=\"multipartFile\"; filename=\""+fileName+"\"", in, ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
        builder.addBinaryBody("multipartFile", in, ContentType.MULTIPART_FORM_DATA, fileName);
        //其他参数        
        for(String key : requestBody.keySet()){
            builder.addTextBody(key, requestBody.get(key).toString(),  ContentType.create("text/plain", Consts.UTF_8));
        }
        //HttpEntity
        HttpEntity entity = builder.build();
        post.setEntity(entity); 
        CloseableHttpResponse response = client.execute(post);
        // 判断返回的状态
        StatusLine status = response.getStatusLine();
        int state = status.getStatusCode();
        logger.warn("返回状态："+state);
        if (state == HttpStatus.SC_OK) {
            HttpEntity responseEntity = response.getEntity();
            String json = EntityUtils.toString(responseEntity, "utf-8");
            response.close();
            client.close();
            return json;
        }
        response.close();
        client.close();
        return null;
    }
    
    /**
     * 发送post请求，使用multipart/form-data的方式传递参数，实现服务器间文件上传功能
     * @param urlStr
     * @param requestHeader
     * @param textMap
     * @param fileMap
     * @return
     */
    public static String doPostMultipart(String urlStr, Map<String, String> requestHeader, Map<String, String> textMap,
            Map<String, String> fileMap) {
        String res = "";
        HttpURLConnection conn = null;
        // boundary就是request头和上传文件内容的分隔符
        String BOUNDARY = "---------------------------"+(new Date()).getTime(); 
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(300000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            // conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            
            //设置Header参数
            conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
            if(requestHeader != null) {
                Iterator iteratorHeader = requestHeader.entrySet().iterator();
                while (iteratorHeader.hasNext()) {
                    Entry<String, String> elem = (Entry<String, String>) iteratorHeader.next();
                    conn.setRequestProperty(elem.getKey(), elem.getValue());
                }
            }
            OutputStream out = new DataOutputStream(conn.getOutputStream());
            
            // 设置字符参数
            if (textMap != null) {
                StringBuffer strBuf = new StringBuffer();
                Iterator iter = textMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Entry entry = (Entry) iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
                    strBuf.append(inputValue);
                }
                out.write(strBuf.toString().getBytes());
            }
            
            // 设置文件参数
            if (fileMap != null) {
                Iterator iter = fileMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Entry entry = (Entry) iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    File file = new File(inputValue);
                    String filename = file.getName();
                    
                    //根据文件获取不到类型，默认采用application/octet-stream
                    String contentType = new MimetypesFileTypeMap().getContentType(file);
                    //contentType非空采用filename匹配默认的图片类型
                    if(!"".equals(contentType)){
                        if (filename.endsWith(".png")) {
                            contentType = "image/png"; 
                        }else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
                            contentType = "image/jpeg";
                        }else if (filename.endsWith(".gif")) {
                            contentType = "image/gif";
                        }else if (filename.endsWith(".ico")) {
                            contentType = "image/image/x-icon";
                        }
                    }
                    if (contentType == null || "".equals(contentType)) {
                        contentType = "application/octet-stream";
                    }
                    StringBuffer strBuf = new StringBuffer();
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                    out.write(strBuf.toString().getBytes());
                    try(DataInputStream in = new DataInputStream(new FileInputStream(file))){
	                    int bytes = 0;
	                    byte[] bufferOut = new byte[1024];
	                    while ((bytes = in.read(bufferOut)) != -1) {
	                        out.write(bufferOut, 0, bytes);
	                    }
	                    in.close();
                    }
                }
            }
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();
            // 读取返回数据
            InputStream is = conn.getInputStream();
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int n = 0;
            while (-1 != (n = is.read(buffer))) {
                output.write(buffer, 0, n);
            }
            res = Base64.getEncoder().encodeToString(output.toByteArray()); 
        } catch (Exception e) {
            logger.error("发送POST（multipart/form-data）请求出错。" + urlStr);
            e.printStackTrace();
            logger.error(e.getMessage());
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }
    
    public static byte[] doPostMultipartFormData(String Url, Map<String, String> requestHeader, Map<String, Object> requestBody, File file) throws IOException {
        // 创建一个httpclient对象
        //超时处理
        RequestConfig config = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(5000).setConnectionRequestTimeout(5000).setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
        CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();
        //CloseableHttpClient client = HttpClients.createDefault();
        // 创建一个post对象
        HttpPost post = new HttpPost(Url);
        // 设置requestHeader参数
        if(requestHeader!=null) {
            Iterator iteratorHeader = requestHeader.entrySet().iterator();
            while (iteratorHeader.hasNext()) {
                Entry<String, String> elem = (Entry<String, String>) iteratorHeader.next();
                post.setHeader(elem.getKey(), elem.getValue());
            }
        }
        String BOUNDARY = UUID.randomUUID().toString();
        post.addHeader("Content-Type", "multipart/form-data; boundary="+BOUNDARY);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        //字符编码
        builder.setCharset(Charset.forName("UTF-8"));
        //模拟浏览器
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        //boundary
        builder.setBoundary(BOUNDARY);
        
        //其他参数        
        for(String key : requestBody.keySet()){
            builder.addTextBody(key, requestBody.get(key).toString(),  ContentType.create("text/plain", Consts.UTF_8));
        }
        
        //multipart/form-data 
        builder.addPart("multipartFile",new FileBody(file));
        // binary //
//        builder.addBinaryBody("name=\"stream\"; filename=\""+fileName+"\"", in, ContentType.MULTIPART_FORM_DATA, fileName);// 文件流 

        
        //HttpEntity
        HttpEntity entity = builder.build();
        post.setEntity(entity); 
        CloseableHttpResponse response = client.execute(post);
        // 判断返回的状态
        StatusLine status = response.getStatusLine();
        int state = status.getStatusCode();
        logger.warn("返回状态："+state);
        if (state == HttpStatus.SC_OK) {
            HttpEntity responseEntity = response.getEntity();
            byte[] bytes = EntityUtils.toByteArray(responseEntity);
            response.close();
            client.close();
            return bytes;
        }
        response.close();
        client.close();
        return null;
    }
    
    /**
     * post多个文件请求
     * @param Url
     * @param requestHeader
     * @param requestBody
     * @param MultipartList
     * @return
     * @throws IOException
     */
    public static byte[] doPostMultipartFormData(String Url, Map<String, String> requestHeader, Map<String, Object> requestBody, List<Map<String, Object>> MultipartList) throws IOException {
        // 创建一个httpclient对象
        //超时处理
        RequestConfig config = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(5000).setConnectionRequestTimeout(5000).setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
        CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();
        //CloseableHttpClient client = HttpClients.createDefault();
        // 创建一个post对象
        HttpPost post = new HttpPost(Url);
        // 设置requestHeader参数
        if(requestHeader!=null) {
            Iterator iteratorHeader = requestHeader.entrySet().iterator();
            while (iteratorHeader.hasNext()) {
                Entry<String, String> elem = (Entry<String, String>) iteratorHeader.next();
                post.setHeader(elem.getKey(), elem.getValue());
            }
        }
        String BOUNDARY = UUID.randomUUID().toString();
        post.addHeader("Content-Type", "multipart/form-data; boundary="+BOUNDARY);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        //字符编码
        builder.setCharset(Charset.forName("UTF-8"));
        //模拟浏览器
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        //boundary
        builder.setBoundary(BOUNDARY);
        
        for (Map<String, Object> map : MultipartList) {
            builder.addBinaryBody(map.get("name").toString(), (File) map.get("file"), ContentType.MULTIPART_FORM_DATA, map.get("fileName").toString());// 文件流 
        }
        //其他参数        
        for(String key : requestBody.keySet()){
            builder.addTextBody(key, requestBody.get(key).toString(),  ContentType.create("text/plain", Consts.UTF_8));
        }
        
        //HttpEntity
        HttpEntity entity = builder.build();
        post.setEntity(entity); 
        CloseableHttpResponse response = client.execute(post);
        // 判断返回的状态
        StatusLine status = response.getStatusLine();
        int state = status.getStatusCode();
        logger.warn("返回状态："+state);
        if (state == HttpStatus.SC_OK) {
            HttpEntity responseEntity = response.getEntity();
            byte[] bytes = EntityUtils.toByteArray(responseEntity);
            response.close();
            client.close();
            return bytes;
        }
        response.close();
        client.close();
        return null;
    }
    

    /**
     * 
     * 调用http(post)接口
     * @param Url
     * @param requestHeader
     * @param requestBody
     * @return
     * @throws IOException
     * <br/>==============History===============<br/>
     * 2019年7月22日   admin    新建
     */
    public static Map<String,String> doPostNew(String Url, Map<String, String> requestHeader, Map<String, Object> requestBody) throws IOException {
        // 创建一个httpclient对象
        Map<String,String> tempMap = new HashMap<String,String>();
        try(CloseableHttpClient client = HttpClients.createDefault()){
	        // 创建一个post对象
	        HttpPost post = new HttpPost(Url);
	        ObjectMapper mapper = new ObjectMapper();
	        // 设置requestHeader参数
	        Iterator iteratorHeader = requestHeader.entrySet().iterator();
	        while (iteratorHeader.hasNext()) {
	            Entry<String, String> elem = (Entry<String, String>) iteratorHeader.next();
	            post.setHeader(elem.getKey(), elem.getValue());
	        }
	        // 设置requestBody参数
	        StringEntity requestJson = new StringEntity(mapper.writeValueAsString(requestBody), "utf-8");
	        requestJson.setContentType("application/json");
	        post.setEntity(requestJson);
	        CloseableHttpResponse response = client.execute(post);
	        // 判断返回的状态
	        StatusLine status = response.getStatusLine();
	        int state = status.getStatusCode();
	        logger.warn("返回状态："+state);
	        if (state == HttpStatus.SC_OK) {
	            HttpEntity responseEntity = response.getEntity();
	            String json = EntityUtils.toString(responseEntity, "utf-8");
	            response.close();
	            client.close();
	            tempMap.put("code", state+"");
	            tempMap.put("json", json);
	            return tempMap;
	        }
	        response.close();
	        client.close();
	        tempMap.put("code", state+"");
	        HttpEntity responseEntity = response.getEntity();
	        String json = "";
	        if(responseEntity != null) {
	            json = responseEntity.toString();
	        }
	        tempMap.put("json", json);
        }
        return tempMap;
    }


    /**
     * 发送get请求；带请求头和请求参数
     * @param url 请求地址
     * @param headers 请求头集合
     * @param params 请求参数集合
     */
    public static String doTycGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建访问的地址
        URIBuilder uriBuilder = new URIBuilder(url);
        if (params != null) {
            Set<Entry<String, String>> entrySet = params.entrySet();
            for (Entry<String, String> entry : entrySet) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue());
            }
        }

        // 创建http对象
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        /**
         * setConnectTimeout：设置连接超时时间，单位毫秒。
         * setConnectionRequestTimeout：设置从connect Manager(连接池)获取Connection
         * 超时时间，单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的。
         * setSocketTimeout：请求获取数据的超时时间(即响应时间)，单位毫秒。 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用。
         */
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(6000).setSocketTimeout(6000).build();
        httpGet.setConfig(requestConfig);

        // 设置请求头
        packageHeader(headers, httpGet);

        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = null;

        try {
            // 执行请求并获得响应结果
            return getHttpClientResult(httpResponse, httpClient, httpGet);
        } finally {
            // 释放资源
            release(httpResponse, httpClient);
        }
    }

    /**
     * 封装请求头
     */
    public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
        if (params != null) {
            Set<Entry<String, String>> entrySet = params.entrySet();
            for (Entry<String, String> entry : entrySet) {
                httpMethod.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * 获得响应结果
     */
    public static String getHttpClientResult(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
        // 执行请求
        httpResponse = httpClient.execute(httpMethod);

        // 获取返回结果
        if (httpResponse != null && httpResponse.getStatusLine() != null) {
            String content = "";
            if (httpResponse.getEntity() != null) {
                content = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
            }
            return content;
        }

        return "";
    }

    /**
            * 释放资源
     */
    public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
        if (httpResponse != null) {
            httpResponse.close();
        }
        if (httpClient != null) {
            httpClient.close();
        }
    }

}
